<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\Db;
use cmf\controller\AdminBaseController;
use app\admin\model\AdminMenuModel;
use Hooklife\ThinkphpWechat\Wechat;
use EasyWeChat\Foundation\Application;
class WechatController extends AdminBaseController{

    public function _initialize(){
        $this->user_id = cmf_get_current_admin_id();
//        $this->query = Db::name('wx_info')->where('user_id', $this->user_id)->count();
        $this->query = '1';
        $this->info = Db::name('wx_info')->where('user_id', $this->user_id)->find();
        if (!empty($this->info)) {
            $options = [
                'app_id' => $this->info['app_id'],         // AppID
                'secret' => $this->info['app_secret'],     // AppSecret
                'token' => $this->info['token'],          // Token
                'aes_key' => $this->info['aes_key'],                 // EncodingAESKey，安全模式下请一定要填写！！！
            ];
            $this->app = new Application($options);
            $this->app_id = $this->info['app_id'];
            $this->secret = $this->info['app_secret'];
            $this->token = $this->info['token'];
        } else {
            if($this->user_id != '1'){
                echo "<div id='notice'><h1>还没有添加公众号，请先添加公众号</h1><br><a href='http://".$_SERVER['HTTP_HOST']."/Admin/wechat/editPublic.html'>点击跳转配置公众号</a></div>";
            }
        }
    }
//    编辑公众号
    public function editPublic(){
        echo "<style type='text/css'>#notice{display: none;}</style>";
//        $info = Db::name('wx_info')->where('user_id',$this->user_id)->find();
        $info = Db::table('wy_wx_info')
            ->alias('a')
            ->join('hatProvince e','a.province = e.provinceID','left')
            ->join('hatCity c','a.city = c.cityID','left')
            ->join('hatArea d','a.area = d.areaID','left')
            ->where('a.user_id',$this->user_id)
            ->field('a.*,e.province as pName,c.city as cityName,d.area as areaName')
            ->find();
        if(!empty($info['id'])){
            $this->assign('info',$info);
        }
        return $this->fetch();
    }
    public function saveEditPublic(){
        $data = input();
        $file = request()->file('imgsrc');

        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
            if($info){
                $data['imgsrc'] = $info->getSaveName();
            }
        }
        $data['user_id'] = $this->user_id;
        $id = input('id');
        if(!empty($id)){
            $res = Db::name('wx_info')->where(['id'=>$id,'user_id'=>$this->user_id])->update($data);
        }else{
            $data['time'] = time();
            $res = Db::name('wx_info')->insert($data);
        }
        self::menu();
        if($res){
            $this->success('添加成功','editPublic');
        }
    }
//    同步粉丝
    public function updateFansList(){
        if($this->query){
            $userService = $this->app->user;
            $lists = $userService->lists();
            $data = $userService->batchGet($lists['data']['openid']);
            foreach ($data['user_info_list'] as $v){
                $v['user_id'] = $this->user_id;
                $v['tagid_list'] = implode(',',$v['tagid_list']);
                $res = Db::name('wx_fans')->where('openid',$v['openid'])->find();
                if($res){
                    Db::name('wx_fans')->where('openid',$v['openid'])->update($v);
                }else{
                    Db::name('wx_fans')->insert($v);
                }

            }
//            $res = Db::name('wx_fans')->where('user_id',$this->user_id)->count();
//            if($res){
//                Db::name('wx_fans')->where('user_id',$this->user_id)->delete();
//                foreach ($data['user_info_list'] as $v){
//                    $v['user_id'] = $this->user_id;
//                    $v['tagid_list'] = implode(',',$v['tagid_list']);
//                    Db::name('wx_fans')->insert($v);
//                }
//            }else{
//                self::menu();
//                foreach ($data['user_info_list'] as $v){
//                    $v['user_id'] = $this->user_id;
//                    $v['tagid_list'] = implode(',',$v['tagid_list']);
//                    Db::name('wx_fans')->insert($v);
//                }
//            }
            $this->success('同步完成',url('fansList'));
        }
    }
//    同步标签
    public function updateTag(){
        if($this->query){
            $res = Db::name('wx_tag')->where('user_id',$this->user_id)->count();
            if($res){
                Db::name('wx_tag')->where('user_id',$this->user_id)->delete();
                $tag = $this->app->user_tag;
                $tagList = $tag->lists();
                foreach ($tagList as $v){
                    foreach ($v as $v1){
                        $v2['tagid_list'] = $v1['id'];
                        $v2['name'] = $v1['name'];
                        $v2['count'] = $v1['count'];
                        $v2['user_id'] = $this->user_id;
                        Db::name('wx_tag')->insert($v2);
                    }
                }
            }else{
                $tag = $this->app->user_tag;
                $tagList = $tag->lists();
                foreach ($tagList as $v){
                    foreach ($v as $v1){
                        $v2['tagid_list'] = $v1['id'];
                        $v2['name'] = $v1['name'];
                        $v2['count'] = $v1['count'];
                        $v2['user_id'] = $this->user_id;
                        Db::name('wx_tag')->insert($v2);
                    }
                }
            }
            $this->success('同步完成',url('tagList'));
        }
    }
//    微信粉丝列表
    public function fanslist(){
        if($this->query){
            $data = $this->request->param();
            if($data){
                $keyword = $this->request->param('keyword');
                if($keyword){
                    $where['nickname|remark'] = ['like',"%".$keyword."%"];
                }
                $tagid_list = $this->request->param('tagid_list');
                if($tagid_list){
                    $where['tagid_list'] = $tagid_list;
                    $where['user_id'] = $this->user_id;
                }
                $list = Db::name('wx_fans')
                    ->where($where)
                    ->select();
                $this->assign('list',$list);
                $tag = Db::name('wx_tag')->select();
                $this->assign('tag',$tag);
            }else{
                $list = Db::name('wx_fans')->where('user_id',$this->user_id)->select();
                $this->assign('list',$list);
                $tag = Db::name('wx_tag')->where('user_id',$this->user_id)->select();
                $this->assign('tag',$tag);
            }
        }
        return $this->fetch();
    }
//    更改备注
    public function changeRemark(){
        $remark = $this->request->param('remark');
        $openid = $this->request->param('openid');
        $userService = $this->app->user;
        $res = $userService->remark($openid, $remark);
        if($res){
            $res1 = Db::name('wx_fans')->where('openid',$openid)->update(['remark'=>$remark]);
            if($res1){
                $this->success("成功将备注更改为".$remark);
            }
        }
    }
//    标签列表
    public function tagList(){
        if($this->query){
            $data = $this->request->param();
            if($data){
                $keyword = $this->request->param('keyword');
                $where['name'] = ['like',"%".$keyword."%"];
                $list = Db::name('wx_tag')
                    ->where($where)
                    ->select();
                $this->assign('list',$list);
            }else{
                $list = Db::name('wx_tag')->where('user_id',$this->user_id)->select();
                $this->assign('list',$list);
            }
        }
        return $this->fetch();
    }
//    更改标签
    public function changeTag(){
        $tag = $this->app->user_tag;
        $name = $this->request->param('name');
        $tag_id = $this->request->param('tagid_list');
        $res = $tag->update($tag_id, $name);
        if($res){
            $res1 = Db::name('wx_tag')->where('tagid_list',$tag_id)->update(['name'=>$name]);
            if($res1){
                $this->success("标签修改成功");
            }
        }
    }
//    添加标签
    public function addTag(){
        $tag = $this->app->user_tag;
        $text = $this->request->param('text');
        if($text){
            $count = Db::name('wx_tag')->where('name',$text)->count();
            if($count){
                $this->success("标签名称已存在");
            }else{
                $res = $tag->create($text);
                if($res){
                    $this->success("创建标签成功！正在同步标签");
                }
            }
        }
    }
//    删除标签
    public function delTag(){
        $tag = $this->app->user_tag;
        $tagId = $this->request->param('tagId');
        if($tagId){
            $res = $tag->delete($tagId);
            if($res){
                $delDb = Db::name('wx_tag')->where('tagid_list',$tagId)->delete();
                if($delDb){
                    $this->success("删除标签成功！");
                }
            }
        }
    }

    public function daTag(){
        $tag = $this->app->user_tag;
        $openid = input('openid');
        $tag_id = input('tag_id');
        if(!empty($openid)){
            $openIds = explode(',',$openid);
            if(!empty($tag_id)){
                $tagId = explode(',',$tag_id);
                end($tagId);
                $key_last = key($tagId);
                foreach ($tagId as $k => $v){
                    Wechat::user_tag()->batchTagUsers($openIds, $v);
                    if($k == $key_last){
                        $this->success('标签打取完毕，正在同步粉丝列表，请耐心等待，直到同步完成','updateFansList','6');
                    }
                }
            }else{
                $this->success('至少选取一个标签','','5');
            }
        }else{
            $this->success('至少选取一个用户','','5');
        }
    }

//    生成菜单
    public function menu(){
        $user = Db::name('user')->where('id','1')->find();
        $menu = $this->app->menu;
        $url = "http://".$_SERVER['HTTP_HOST']."/portal/wuye/code?app_id=".$this->app_id;
        $buttons = [
            [
                "name"       => "智慧物业",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "首页",
                        "url"  => $url. '&url=index'
                    ],
                    [
                        "type" => "view",
                        "name" => "缴费管理",
                        "url"  => $url . '&url=pay'
                    ],
                    [
                        "type" => "view",
                        "name" => "物业通知",
                        "url"  => $url . '&url=notice'
                    ],
                    [
                        "type" => "view",
                        "name" => "个人中心",
                        "url"  => $url . '&url=me'
                    ],
                    [
                        "type" => "view",
                        "name" => "办事指南",
                        "url"  => $url . '&url=guide'
                    ],
                ],
            ],[
                "type" => "view",
                "name" => "快捷订菜",
                "url"  => "http://qiangcai.mingruisoft.com/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=quick&id=1"
            ],[
                "name"       => "便民服务",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "装修开锁",
                        "url"  => $url . '&url=wei'
                    ],
                    [
                        "type" => "view",
                        "name" => "家政服务",
                        "url"  => $url . '&url=jia'
                    ],
                    [
                        "type" => "view",
                        "name" => "周边商圈",
                        "url"  => $url . '&url=meituan'
                    ],
                    [
                        "type" => "view",
                        "name" => "房屋租售",
                        "url"  => $url . '&url=lease'
                    ],
                    [
                        "type" => "view",
                        "name" => "车险报价",
                        "url"  => $user['cxbj']
                    ],
                ],
            ],
        ];
        $menu->add($buttons);
    }

//    公众号列表
    public function gzhlist(){
        echo "<style type='text/css'>#notice{display: none;}</style>";
        $data = $this->request->param();
        if($data){
            $keyword = $this->request->param('keyword');
            $where['name'] = ['like',"%".$keyword."%"];
            $list = Db::name('wx_info')
                ->where($where)
                ->select();
        }else{
            $list = Db::name('wx_info')->select();
        }
        $this->assign('list',$list);
        return view();
    }
    public function del(){
        $id = input('id');
        $table = input('table');
        $res = Db::name($table)->delete($id);
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
}
